<template>
  <!-- #ifndef MP-TOUTIAO -->
  <back-nav-bar title="注册"></back-nav-bar>
  <!-- #endif -->
  <view class="register-container">
    <uni-forms ref="form" :model="formData" :rules="rules" class="register-form">
      <uni-forms-item label="账号" name="userName" class="uni-forms-item">
        <uni-easyinput
          type="text"
          v-model="formData.userName"
          placeholder="请输入账号"
          class="input-field"
        />
      </uni-forms-item>
      <uni-forms-item label="昵称" name="nickName" class="uni-forms-item">
        <uni-easyinput
          type="text"
          v-model="formData.nickName"
          placeholder="请输入昵称"
          class="input-field"
        />
      </uni-forms-item>
      <uni-forms-item label="密码" name="password" class="uni-forms-item">
        <uni-easyinput
          type="password"
          v-model="formData.password"
          placeholder="请输入密码"
          class="input-field"
        />
      </uni-forms-item>
      <uni-forms-item label="确认密码" name="confirmPassword" class="uni-forms-item">
        <uni-easyinput
          type="password"
          v-model="formData.confirmPassword"
          placeholder="请再次输入密码"
          class="input-field"
        />
      </uni-forms-item>
      <uni-forms-item label="验证码" name="code" v-if="captchaEnabled" class="uni-forms-item">
        <view class="code-input">
          <uni-easyinput
            type="text"
            v-model="formData.code"
            placeholder="请输入验证码"
            class="input-field"
            style="width: 63%"
          />
          <image :src="codeUrl" @click="getCode" class="register-code-img" />
        </view>
      </uni-forms-item>
    </uni-forms>
    <button @click="submit" class="register-button">注册</button>
    <navigator url="/pages/login/login" hover-class="none" class="login-link"
      >已有账号？去登录</navigator
    >
  </view>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { getCodeImg, register } from '@/api/auth'
import { toast } from '@/utils/common'
import BackNavBar from '@/components/back-nav-bar/back-nav-bar.vue'

const formData = reactive({
  userName: '',
  nickName: '',
  password: '',
  confirmPassword: '',
  code: '',
  uuid: '',
})

const rules = reactive({
  userName: {
    rules: [
      {
        required: true,
        errorMessage: '请输入账号',
      },
    ],
  },
  nickName: {
    rules: [
      {
        required: true,
        errorMessage: '请输入昵称',
      },
    ],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码',
      },
    ],
  },
  confirmPassword: {
    rules: [
      {
        required: true,
        validator: (rule, value) => {
          if (value !== formData.password) {
            return new Error('两次输入的密码不一致')
          }
          return true
        },
        errorMessage: '两次输入的密码不一致',
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: '请输入验证码',
      },
    ],
  },
})

const codeUrl = ref('')
const captchaEnabled = ref(true)
const loading = ref(false)

const form = ref(null)

const getCode = async () => {
  try {
    const res = await getCodeImg()
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${res.img}`
      formData.uuid = res.uuid
    }
  } catch (error) {
    console.error('获取验证码失败', error)
  }
}

const submit = async () => {
  loading.value = true
  uni.showLoading({
    title: '注册中...',
  })

  try {
    await form.value.validate().then(async () => {
      await register(formData)
        .then((res) => {
          console.log(res)
          toast(`恭喜你，您的账号 ${formData.nickName} 注册成功！`)
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' })
          }, 1500)
        })
        .catch((error) => {
          toast('注册失败,' + error)
        })
    })
  } catch (err) {
    console.error('表单验证失败', err)
    if (captchaEnabled.value) {
      getCode()
    }
  } finally {
    loading.value = false
    uni.hideLoading()
  }
}

getCode()
</script>
<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 20rpx;
}

.register-form {
  width: 100%;
  max-width: 360px;
}

.uni-forms-item {
  margin-bottom: 20rpx;
}

.input-field {
  width: 100%;
  padding: 10rpx;
  border: 1rpx solid #ccc;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.uni-forms-item .title {
  font-weight: bold;
}

.code-input {
  display: flex;
  align-items: center;
}

.register-code-img {
  cursor: pointer;
  vertical-align: middle;
  height: 40px;
  width: 120px;
  padding-left: 12px;
  border-radius: 8rpx;
}

.register-button {
  width: 100%;
  max-width: 360px;
  padding: 12rpx 0;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  cursor: pointer;
  transition: background-color 0.3s;
}

.register-button:hover {
  background-color: #40a9ff;
}

.login-link {
  width: 100%;
  max-width: 360px;
  text-align: right;
  color: #1890ff;
  margin-top: 10rpx;
  font-size: 28rpx;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}
</style>
